package gui;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.border.LineBorder;

import server.PlayerServer;

public class AddCritterFrame extends JFrame {
	private PlayerServer playerServer;
	private WorldViewPanel view;
	
	private JPanel containerPanel;
	private JTextField critterFileText;
	private Box buttonBox;
	private JButton addButton;
	private JButton cancelButton;

	private final Color bkg = new Color(255,99,71);

	public AddCritterFrame(PlayerServer server, WorldViewPanel v) {
		playerServer = server;
		view = v;

		setSize(500, 150);
		setTitle("Add a critter from file");
		containerPanel = new JPanel();
		containerPanel.setLayout(new GridLayout(0,1));
		containerPanel.setBorder(new LineBorder(bkg, 3));
		add(containerPanel);
		
		containerPanel.add(new JLabel("File to load new critters from:", SwingConstants.LEFT));
		critterFileText = new JTextField();
		containerPanel.add(critterFileText);
		
		buttonBox = new Box(BoxLayout.X_AXIS);
		containerPanel.add(buttonBox);

		addButton = new JButton("Add Critter");
		addButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				try {
					final StringBuffer sb = new StringBuffer();
					Scanner critScanner = new Scanner(new File(critterFileText.getText()));
					while(critScanner.hasNext())
						sb.append(critScanner.nextLine() + "\n");
					SwingWorker<String, Object> uploader = new SwingWorker<String, Object>(){
						protected String doInBackground() throws Exception {
							return playerServer.uploadCritter(sb.toString());
						}
						protected void done(){
							try{
								get();
								SwingUtilities.getRootPane(view).repaint();
								SwingUtilities.getWindowAncestor(addButton).dispose();
							} catch (Exception e1) {
								JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(addButton),
										e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
							}
						}
					};
					uploader.execute();
				} catch (FileNotFoundException e1) {
					JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(addButton),
							e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		});

		cancelButton = new CancelButton();
		buttonBox.add(addButton);
		buttonBox.add(Box.createHorizontalStrut(20));
		buttonBox.add(cancelButton);
		
		containerPanel.setBackground(bkg);
		setVisible(true);
	}
}
